package test.xinhe.perf.gatling.test.common

import java.io.{BufferedReader, IOException, InputStream, InputStreamReader}

import ch.ethz.ssh2.{Connection, Session, StreamGobbler}


class RemoteShellTool(ipAddr: String, post: Int, userName: String, password: String) {

  val conn: Connection = new Connection(ipAddr, post)

  //判断是否连接上了
  def login(): Boolean = {
    conn.connect()
    // 连接
    val ret: Boolean = conn.authenticateWithPassword(userName, password)
    ret
  }

  //发送命令过去
  def exec(cmds: String): String = {
    var result: String = ""
    try {
      val str_ret: Boolean = login()
      if (str_ret) {
        // 打开一个会话
        val session = conn.openSession()
        session.execCommand(cmds)
        val in = session.getStdout
        result = processStdout(in)
      } else {
        println("连接失败")
      }
    } catch {
      case e: IOException => {
        e.printStackTrace()
      }
    } finally {
      conn.close()
    }
    result
  }

  //处理返回结果
  def processStdout(in: InputStream): String = {
    val is = new StreamGobbler(in)
    val brs: BufferedReader = new BufferedReader(new InputStreamReader(is))
    val line = brs.lines().toArray().toList.mkString(",")
    line
  }
}